package tpf.designer.pattern.course5.structure_pattern2.flyweight_13.simple;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 在享元模式中，有一个至关重要的模块就是工厂模块了。
 * 在 Flyweight Factory 里维护了一个 Flyweight池(存放内部状态)，
 * Flyweight Factory 就是通过这个 Flyweight 池对整个享元模式进行控制。
 */
public class FlyweightFactory {

    private HashMap flies = new HashMap();
    private Flyweight lnkFlyweight;
    private Map<Integer, Flyweight> labels = new HashMap<Integer, Flyweight>();

    /**
     * 默认构造函数
     */
    public FlyweightFactory() {
    }

    /**
     * 内蕴状态作为参量传入
     * @param state
     */
    public Flyweight factory(Character state) {
        if (flies.containsKey(state)){
            return (Flyweight)flies.get(state);
        } else {
            Flyweight fly = new ConcreteFlyweight(state);
            flies.put(state,fly);
            return fly;
        }
    }
    /*public Flyweight factory(Character intrinsicState) {
        int hashCode = intrinsicState.hashCode();
        Flyweight fly = labels.get(hashCode);
        if (fly == null) {
            fly = new ConcreteFlyweight(intrinsicState);
            labels.put(hashCode, fly);
        }
        return fly;
    }*/

    /**
     * 辅助方法
     */
    public void checkFlyweight(){
        Flyweight fly;
        int i = 0;
        System.out.println("\n===================checkFlyweight===================\n");
        for (Iterator it = flies.entrySet().iterator(); it.hasNext(); ){
            Map.Entry e = (Map.Entry)it.next();
            System.out.println("享元对象" + (++i) + ":" + e.getKey());
        }
        System.out.println("\n===================checkFlyweight===================\n");
    }
}
